import pandas as pd
from sklearn.ensemble import AdaBoostRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import pickle
import util

modelName = '3ap'

Xcols = ['eirp', 'mcs', 'nss', 'seq_time',
          'ap_from_ap_0_max_ant_rssi', 'ap_from_ap_0_mean_ant_rssi', 'ap_from_ap_0_sum_ant_rssi',
        'ap_from_ap_1_max_ant_rssi', 'ap_from_ap_1_mean_ant_rssi', 'ap_from_ap_1_sum_ant_rssi',
          'sta_from_ap_0_max_ant_rssi', 'sta_from_ap_0_mean_ant_rssi', 'sta_from_ap_0_sum_ant_rssi',
          'sta_from_ap_1_max_ant_rssi', 'sta_from_ap_1_mean_ant_rssi', 'sta_from_ap_1_sum_ant_rssi',
        'sta_from_ap_2_max_ant_rssi', 'sta_from_ap_2_mean_ant_rssi', 'sta_from_ap_2_sum_ant_rssi',
          'sta_to_ap_0_max_ant_rssi', 'sta_to_ap_0_mean_ant_rssi', 'sta_to_ap_0_sum_ant_rssi',
          'sta_to_ap_1_max_ant_rssi', 'sta_to_ap_1_mean_ant_rssi', 'sta_to_ap_1_sum_ant_rssi',
        'sta_to_ap_2_max_ant_rssi', 'sta_to_ap_2_mean_ant_rssi', 'sta_to_ap_2_sum_ant_rssi']

data = pd.read_csv('reduceRssi_' + modelName + '_enhancement.csv')
missing_values = data[Xcols].isnull().any(axis=1)
data = data[~missing_values]
print('data len', len(data))

# 提取输入特征和目标列
X = data[Xcols]
y = data['throughput']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)

# 创建AdaBoost回归模型
adaboost = AdaBoostRegressor()
adaboost.fit(X_train, y_train)

# 保存模型
with open(modelName + '_throughput.pkl', 'wb') as f:
    pickle.dump(adaboost, f)

util.getAdaboostImportance(adaboost, Xcols)

# 跑测试数据
def predTestCsv(filename):
    testData = pd.read_csv(filename)
    testX = testData[Xcols]
    testY = adaboost.predict(testX)
    # print(testY)
    testData['throughput'] = pd.Series(testY)
    testData.to_csv(filename)
predTestCsv('test_set_1_' + modelName + '_ReduceRssi_pred.csv')
predTestCsv('test_set_2_' + modelName + '_ReduceRssi_pred.csv')

# 计算拆分的测试集的均方误差
y_pred = adaboost.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)